package com.qidian.mq.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @date 2023/5/25 11:35
 */
@Configuration
public class RabbitMQConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        // 这里的参数connectionFactory spring提供的
        rabbitTemplate.setConnectionFactory(connectionFactory);
        // 开启Mandatory, 才能触发回调函数，无论消息推送结果如何都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        //设置确认回调 (我们使用匿名内部类实现) 当然也可以使用lamda表达式
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("ConfirmCallback: "+"相关数据：" + correlationData);
                System.out.println("ConfirmCallback: "+"确认情况：" + ack);
                System.out.println("ConfirmCallback: "+"原因：" + cause);
            }
        });

        //返回的回调函数  (这里使用lamda表达式实现)
        rabbitTemplate.setReturnCallback((message,replyCode,replyText,exchange,routingKey)->{
            System.out.println("ReturnCallback: "+"消息：" + message);
            System.out.println("ReturnCallback: "+"回应码：" + replyCode);
            System.out.println("ReturnCallback: "+"回应信息：" + replyText);
            System.out.println("ReturnCallback: "+"交换机：" + exchange);
            System.out.println("ReturnCallback: "+"路由键：" + routingKey);
        });
        return rabbitTemplate;
    }
}
